import { Card, Button, Select, Input, Table, Tag, Modal } from 'antd';
import { useEffect, useState } from 'react';
import type { ColumnsType } from 'antd/es/table';
import { useSetState } from 'react-use';
import { NamespaceService } from '../namespace/service';
import { SvcService } from './service';
import Service, { ListReq, ListResp } from './vms';

import styles from './index.less';
import { useRequest } from 'umi';

export default function ServiceIndex() {
  const [filter, setFilter] = useSetState<ListReq>({});
  const [name, setName] = useState<string>('');

  const [resp, setResp] = useSetState<ListResp>({ total: 0, items: [] });

  const handleChange = (namespace: string) => {
    setFilter({ namespace });
  };

  const list = useRequest(SvcService.list, {
    manual: true,
    onSuccess: (data) => {
      setResp(data);
    },
  });

  const [options, setOptions] = useState<
    {
      value: string;
      label: string;
    }[]
  >();

  const deleteFunc = useRequest(SvcService.delete, {
    manual: true,
    onSuccess: () => {
      list.refresh();
    },
  });

  const columns: ColumnsType<Service> = [
    {
      title: '名称',
      dataIndex: 'service_name',
      key: 'service_name',
    },
    {
      title: '名称空间',
      dataIndex: 'namespace',
      key: 'namespace',
    },
    {
      title: 'selector',
      dataIndex: 'selector',
      key: 'selector',
      render: (_, record) => record.service.spec.selector.app,
    },
    {
      title: 'type',
      dataIndex: 'type',
      key: 'type',
      render: (_, record) => record.service.spec.type,
    },
    {
      title: 'clusterIP',
      dataIndex: 'clusterIP',
      key: 'clusterIP',
      render: (_, record) => record.service.spec.clusterIP,
    },
    {
      title: 'ports',
      dataIndex: 'ports',
      key: 'ports',
      render: (_, { service }) =>
        service.spec.ports.map((item) => (
          <Tag
            key={`${item.protocol}-po(${item.port})-tpo(${item.targetPort})${service.spec.type === 'NodePort' ? `-npo(${item.nodePort})` : ''
              }`}
          >{`${item.protocol}-po(${item.port})-tpo(${item.targetPort})${service.spec.type === 'NodePort' ? `-npo(${item.nodePort})` : ''
            }`}</Tag>
        )),
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      key: 'create_time',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Button
          type="link"
          onClick={() => {
            Modal.confirm({
              title: '删除Service!',
              content: '删除是不可逆操作',
              cancelText: '取消',
              okText: '确定删除',
              onOk: () => {
                return deleteFunc.run({
                  name: record.service_name,
                  namespace: record.namespace,
                });
              },
            });
          }}
        >
          删除
        </Button>
      ),
    },
  ];

  useEffect(() => {
    NamespaceService.list().then((res) => {
      setOptions(
        res.data?.names?.map((name) => ({
          value: name,
          label: name,
        })),
      );
    });
  }, []);

  useEffect(() => {
    list.run(filter);
  }, [filter]);

  return (
    <Card
      className={styles.deploy}
      title={
        <>
          <Select
            style={{ width: 120 }}
            value={filter.namespace}
            onChange={handleChange}
            placeholder="namespace"
            allowClear
            options={options}
          />

          <Input
            value={name}
            className={styles.inputName}
            placeholder="输入关键词"
            onChange={(e) => setName(e.target.value)}
            // @ts-ignore
            onPressEnter={(e) => setFilter({ name: e.target.value })}
          />
        </>
      }
      extra={<Button type="link" onClick={() => {
        Modal.confirm({
          title: '新建SVC?',
          content: '暂时不支持',
          okText: '确认',
          okType: 'danger',
          cancelText: ' 取消',
          onOk() {
            console.log('OK');
          },
          onCancel() {
            console.log('Cancel');
          },
        });
      }}>新建SVC</Button>}
    >
      <Table
        rowKey={(record) => JSON.stringify(record)}
        columns={columns}
        loading={list.loading}
        dataSource={resp.items}
        pagination={{
          total: resp.total,
          pageSize: 20,
        }}
      />
    </Card>
  );
}
